package cn.com.nes.site.service.system.h5.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.CopyUtils;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.mybatis.agent.activity.entity.Activity;
import cn.com.nes.mybatis.agent.activity.entity.TActivityCollect;
import cn.com.nes.mybatis.agent.activity.mapper.ActivityMapper;
import cn.com.nes.mybatis.agent.activity.mapper.TActivityCollectMapper;
import cn.com.nes.mybatis.agent.system.entity.Poster;
import cn.com.nes.mybatis.agent.system.entity.PosterDynamicButton;
import cn.com.nes.mybatis.agent.system.mapper.PosterDynamicButtonMapper;
import cn.com.nes.mybatis.agent.system.mapper.PosterMapper;
import cn.com.nes.site.controller.system.vo.*;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.service.system.h5.NewH5Service;
import cn.com.nes.site.service.system.h5.dto.ActivityDTO;
import cn.com.nes.site.service.system.h5.dto.GetPosterDetailDTO;
import cn.com.nes.site.service.system.h5.dto.PosterDynamicButtonEntity;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.*;

/**
 * v2 版本H5 Service
 *
 * @Author: ShenWei
 * @Date: 2024/07/29/13:32
 */
@Service
@Slf4j
public class NewH5ServiceImpl implements NewH5Service {

    @Resource
    private PosterMapper posterMapper;

    @Resource
    private PosterDynamicButtonMapper posterDynamicButtonMapper;

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private TActivityCollectMapper tActivityCollectMapper;

    private static final Integer NEW_POSTER_TYPE = 1;

    @Override
    public PageData getPosterDetail(GetPosterDetailVO vo) throws Exception {
        LambdaQueryWrapper<Poster> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Poster::getUuid, vo.getUuid());
        List<Poster> posters = posterMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(posters)) {
            return PageData.error("海报信息不存在");
        }
        // 获取海报信息主体
        GetPosterDetailDTO posterDetail = CopyUtils.copyList(posters, GetPosterDetailDTO.class).get(0);
        posterDetail.setIsshow(posters.get(0).getIsShow());
        posterDetail.setCluesource(posters.get(0).getClueSource());
        posterDetail.setBackgroundcolor(posters.get(0).getBackGroundColor());
        posterDetail.setIsshowcode(posters.get(0).getIsShowCode());
        // 设置图片信息
        posterDetail.setBgimgMap(setImageUrl(posterDetail.getBgimg()));
        posterDetail.setCodebgimgMap(setImageUrl(posterDetail.getCodebgimg()));
        posterDetail.setCodeimgMap(setImageUrl(posterDetail.getCodeimg()));
        posterDetail.setHeadimgMap(setImageUrl(posterDetail.getHeadimg()));
        posterDetail.setImglistMap(setImageUrl(posterDetail.getImglist()));
        posterDetail.setShareimgMap(setImageUrl(posterDetail.getShareimg()));

        // 设置海报的按钮信息
        setDynamicButtonInfo(posterDetail);

        return PageData.ok("posterDetail", posterDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData savePoster(SavePosterVO vo) throws Exception {
        // 保存主体信息
        Poster poster = getPoster(vo);

        Integer rows = 0;
        if (StrUtil.isBlank(poster.getUuid())) {
            poster.setCreateUid(String.valueOf(vo.getOperateUserId()));
            poster.setCreateTime(vo.getOperateDate());
            rows = posterMapper.insert(poster);
        } else {
            rows = posterMapper.update(poster, new QueryWrapper<Poster>().eq("uuid", poster.getUuid()));
        }
        if (rows != 1) {
            throw new IllegalBusinessException("保存海报信息失败!");
        }

        // 删除旧的全部按钮信息
        PosterDynamicButton delButton = new PosterDynamicButton();
        delButton.setPosterUuid(poster.getUuid());
        delButton.setGmtModifiedId(Long.valueOf(vo.getUserInfo().getId()));
        delButton.setGmtModified(new Date());

        log.info("删除动态按钮,button:{}", delButton);
        posterDynamicButtonMapper.delDynamicButtonInfo(delButton);

        // 保存按钮信息
        List<PosterDynamicButtonEntity> btnmesglist = vo.getBtnmesglist();
        if (CollectionUtil.isEmpty(btnmesglist)) {
            return PageData.ok();
        }

        // 插入新的按钮信息
        for (PosterDynamicButtonEntity entity : btnmesglist) {
            PosterDynamicButton button = new PosterDynamicButton();
            copyButtonInstance(entity, button, false);
            button.setPosterUuid(poster.getUuid());
            button.setDeleted(false);
            button.setGmtCreate(vo.getOperateDate());
            button.setGmtCreateId(vo.getOperateUserId());
            button.setGmtModified(vo.getOperateDate());
            button.setGmtModifiedId(vo.getOperateUserId());
            posterDynamicButtonMapper.insert(button);
        }
        PageData pageData = PageData.ok();
        pageData.setKey(poster.getUuid());
        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delPosterButtonInfo(DelPosterButtonInfoVO vo) throws Exception {
        PosterDynamicButton button = new PosterDynamicButton();
        button.setPosterUuid(vo.getPosterUuid());
        button.setGmtModifiedId(Long.valueOf(vo.getUserInfo().getId()));
        button.setGmtModified(new Date());

        log.info("删除动态按钮,button:{}", button);
        // 删除动态按钮信息
        posterDynamicButtonMapper.delDynamicButtonInfo(button);
    }

    // 组装Poster对象
    private Poster getPoster(SavePosterVO vo) {
        Poster poster = new Poster();
        poster.setUuid(vo.getUuid());
        poster.setIsShow(vo.getIsshow());
        poster.setActiveName(vo.getActiveName());
        poster.setClueSource(vo.getCluesource());
        poster.setPlatform(vo.getPlatform());
        poster.setBackGroundColor(vo.getBackgroundcolor());
        poster.setShareimg(vo.getShareimg());
        poster.setHeadimg(vo.getHeadimg());
        poster.setBgimg(vo.getBgimg());
        poster.setImglist(vo.getImglist());
        poster.setCodeimg(vo.getCodeimg());
        poster.setCodebgimg(vo.getCodebgimg());
        poster.setCompanyId(vo.getOperateUserCompanyId());
        poster.setModifyUid(String.valueOf(vo.getOperateUserId()));
        poster.setModifyTime(vo.getOperateDate());
        poster.setIsDelete("");
        poster.setPosterType(ObjectUtil.isNotNull(vo.getPosterType()) ? vo.getPosterType() : NEW_POSTER_TYPE);
        poster.setIsShowCode(vo.getIsshowcode());
        return poster;
    }


    // 设置海报的按钮信息
    private void setDynamicButtonInfo(GetPosterDetailDTO posterDetail) throws Exception {
        // 准备出参
        List<PosterDynamicButtonEntity> PosterDynamicButtonEntityList = new ArrayList<>();
        // 查询按钮信息列表
        LambdaQueryWrapper<PosterDynamicButton> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PosterDynamicButton::getPosterUuid, posterDetail.getUuid());
        wrapper.eq(PosterDynamicButton::getDeleted, false);
        List<PosterDynamicButton> posterDynamicButtons = posterDynamicButtonMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(posterDynamicButtons)) {
            return;
        }
        // 转换按钮信息字段
        for (PosterDynamicButton button : posterDynamicButtons) {
            PosterDynamicButtonEntity entity = new PosterDynamicButtonEntity();
            copyButtonInstance(entity, button, true);

            entity.setImgbtnMap(setImageUrl(entity.getImgbtn()));
            PosterDynamicButtonEntityList.add(entity);
        }
        posterDetail.setBtnmesglist(PosterDynamicButtonEntityList);
    }

    /**
     * 复制海报按钮实体
     * @param entity    出参/入参对象
     * @param button    海报按钮对象
     * @param flag      复制方向 true-按钮对象转出参/入参对象 false-出参/入参对象转按钮对象
     */
    private void copyButtonInstance(PosterDynamicButtonEntity entity, PosterDynamicButton button, Boolean flag) throws Exception {
        // 参数校验
        if (ObjectUtil.isNull(entity) || ObjectUtil.isNull(button)) {
            throw new MissBusinessParameterException("动态按钮实体");
        }
        if (ObjectUtil.isNull(flag)) {
            throw new MissBusinessParameterException("复制方向");
        }
        // 开始复制
        if (flag) {
            entity.setName(button.getName());
            entity.setShowflag(button.getShowFlag());
            entity.setBtnname(button.getButtonName());
            entity.setType(button.getButtonType());
            entity.setPosition(button.getButtonPosition());
            entity.setMesg(button.getContactPhone());
            entity.setUrl(button.getUrl());
            entity.setImgbtn(button.getButtonImageUrl());
        } else {
            button.setName(entity.getName());
            button.setShowFlag(entity.getShowflag());
            button.setButtonName(entity.getBtnname());
            button.setButtonType(entity.getType());
            button.setButtonPosition(entity.getPosition());
            button.setContactPhone(entity.getMesg());
            button.setUrl(entity.getUrl());
            button.setButtonImageUrl(entity.getImgbtn());
        }
    }

    // 设置图片信息
    private List<String> setImageUrl(String images) {
        // 准备返回值
        List<String> imageUrlList = new ArrayList<>();
        // 处理图片数据
        if(StrUtil.isNotBlank(images)){
            String[] imageList = images.split(";");
            for (String imageUrl : imageList) {
                imageUrlList.add(OssUtil.getImgSignURL(imageUrl, 0));
            }
        }
        return imageUrlList;
    }


    @Override
    public PageData getActiveDetail(GetActiveDetailVO vo) {
        ActivityDTO activityDTO = this.activityMapper.getActiveDetail(vo);
        if (ObjectUtil.isNull(activityDTO)) {
            return PageData.error("活动不存在或已被删除,请确认后再试");
        }

        // 处理背景图
        Map<String, String> map = new HashMap<>();
        map.put("imageName", "背景图");
        map.put("bgimg", StrUtil.EMPTY);
        map.put("realBackgroundImageUrl", StrUtil.EMPTY);
        if (StrUtil.isNotBlank(activityDTO.getImagebg())) {
            String realBackgroundImageUrl = OssUtil.getImgSignURL(activityDTO.getImagebg(), 0);
            map.put("bgimg", activityDTO.getImagebg());
            map.put("realBackgroundImageUrl", realBackgroundImageUrl);
        }
        activityDTO.setBgimgMap(map);

        return PageData.ok("activityDetail", activityDTO);
    }

    @Override
    public PageData saveActive(SaveActiveVO vo) throws Exception {
        // 组装参数
        Activity activity = new Activity();
        BeanUtils.copyProperties(vo, activity);
        activity.setUuid(vo.getUuid());
        activity.setJsondata(URLDecoder.decode(vo.getJsondata(), "UTF-8"));
        activity.setImagebg(vo.getBgimg());
        activity.setModifyuid(String.valueOf(vo.getOperateUserId()));
        activity.setModifytime(vo.getOperateDate());

        // 保存 / 更新
        Integer rows;
        if (StrUtil.isBlank(activity.getUuid())) {
            activity.setUuid(UUID.randomUUID().toString());
            activity.setCompanyid(vo.getOperateUserCompanyId());
            activity.setCreateuid(String.valueOf(vo.getOperateUserId()));
            activity.setCreatetime(vo.getOperateDate());
            activity.setIsdelete(String.valueOf(DeleteEnum._0.getKey()));
            rows = this.activityMapper.insert(activity);
        } else {
            rows = this.activityMapper.update(activity, new LambdaQueryWrapper<Activity>().eq(Activity::getUuid, activity.getUuid()));
        }

        if (rows != 1) {
            throw new IllegalBusinessException("保存活动信息失败!");
        }

        // 修改当前公司的默认活动
        if (StrUtil.isNotBlank(activity.getSfmr()) && "1".equals(activity.getSfmr())) {
            // 获取当前公司默认活动
            LambdaQueryWrapper<Activity> defaultActivityWrapper = new LambdaQueryWrapper<>();
            defaultActivityWrapper.eq(Activity::getCompanyid, vo.getOperateUserCompanyId());
            defaultActivityWrapper.eq(Activity::getSfmr, "1");
            defaultActivityWrapper.ne(Activity::getUuid, activity.getUuid());
            List<Activity> defaultActivityList = this.activityMapper.selectList(defaultActivityWrapper);
            if (CollectionUtil.isNotEmpty(defaultActivityList) && ObjectUtil.isNotNull(defaultActivityList.get(0))) {
                Activity defaultActivity = defaultActivityList.get(0);
                defaultActivity.setModifyuid(String.valueOf(vo.getOperateUserId()));
                defaultActivity.setModifytime(vo.getOperateDate());
                defaultActivity.setSfmr("0");
                int count = this.activityMapper.update(defaultActivity, new LambdaQueryWrapper<Activity>().eq(Activity::getUuid, defaultActivity.getUuid()));
                if (count != 1) {
                    throw new IllegalBusinessException("修改默认活动失败!");
                }
            }
        }

        // 添加收藏
        TActivityCollect tActivityCollect = new TActivityCollect();
        tActivityCollect.setUuid(UUID.randomUUID().toString());
        tActivityCollect.setActiveid(activity.getUuid());
        tActivityCollect.setPhone(vo.getOperateUserPhone());
        tActivityCollect.setCreatetime(vo.getOperateDate());
        this.tActivityCollectMapper.insert(tActivityCollect);

        return PageData.ok("activityUuid", activity.getUuid());
    }
}
